package mysql

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"tanbao2/config"
	"tanbao2/model"
)

var Db *sql.DB
var Db2 *sql.DB

func InitDB() error {
	conf := config.Config
	paramS := fmt.Sprintf(
		"%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local",
		conf.MysqlUser,
		conf.MysqlPwd,
		conf.MysqlHost,
		conf.MysqlPort,
		conf.MysqlDb,
	)
	db, err := openDB(paramS)
	if err != nil {
		return err
	}
	Db = db
	paramS2 := fmt.Sprintf(
		"%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local",
		conf.MysqlUser2,
		conf.MysqlPwd2,
		conf.MysqlHost2,
		conf.MysqlPort2,
		conf.MysqlDb2,
	)

	db, err = openDB(paramS2)
	if err != nil {
		return err
	}
	Db2 = db
	return nil
}

func openDB(paramS string) (*sql.DB, error) {
	db, err := sql.Open("mysql", paramS) // 设置连接数据库的参数
	if err != nil {
		fmt.Println("数据库连接失败")
		return nil, err
	} else {
		fmt.Println("数据库连接成功")
	}
	return db, nil
}

// QueryUserInfo 查询用户信息
func QueryUserInfo(userName string, telPhone string) (*model.UserInfoResponse, error) {
	var user model.UserInfo
	sqlStr := "select * from T_UserInfo where user_name=? or telephone=?"
	err := query(Db, sqlStr, &user, userName, telPhone)
	if err != nil {
		return nil, err
	}

	var userReal model.UserRealInfo
	sqlStr = "select * from T_UserReal where user_id=?"
	err = query(Db, sqlStr, &userReal, user.UserId)
	if err != nil {
		return nil, err
	}

	return &model.UserInfoResponse{
		RealInfo: userReal,
		UserInfo: user,
	}, nil
}

// QueryUserFinance 查询用户流水
func QueryUserFinance(userName string, telPhone string, waterType int, pageStart int, pageSize int) (*model.UserFinanceResponse, error) {
	var user model.UserInfo
	sqlStr := "select * from T_UserInfo where user_name=? or telephone=?"
	err := query(Db, sqlStr, &user, userName, telPhone)
	if err != nil {
		return nil, err
	}

	if pageSize == 0 {
		pageSize = 10
	}
	start := strconv.Itoa(pageStart * pageSize)
	end := strconv.Itoa(pageSize)
	limit := " limit " + start + "," + end
	sqlStr = "select * from T_FinanceRecord where user_id=? and business_id=? " + " order by create_time desc" + limit
	rows, err := Db2.Query(sqlStr, user.UserId, waterType)
	if err != nil {
		return nil, err
	}
	var userFinanceRecordList []model.UserFinanceRecord
	for rows.Next() {
		var userFinanceRecord model.UserFinanceRecord
		if err1 := scanToStruct(rows, &userFinanceRecord); err1 == nil {
			userFinanceRecord.UserName = user.UserName
			userFinanceRecordList = append(userFinanceRecordList, userFinanceRecord)
			continue
		}
	}

	sqlStr = "select count(1) from T_FinanceRecord where user_id=? and business_id=?"
	var count int64
	err = Db2.QueryRow(sqlStr, user.UserId, waterType).Scan(&count)
	if err != nil {
		return nil, err
	}
	return &model.UserFinanceResponse{
		UserFinanceRecordList: userFinanceRecordList,
		Total:                 count,
	}, nil
}

func BatchUserInfoByIds(userIds []int) (*model.BatchUserResponse, error) {
	var uidkeys string
	for i := 0; i < len(userIds); i++ {
		uidkeys += "'" + string(rune(userIds[i])) + "'"
		if i < len(userIds)-1 {
			uidkeys += ","
		}
	}
	var users []model.UserInfo
	sqlStr := "select * from T_UserInfo where user_id in (" + uidkeys + ")"
	rows, err := Db.Query(sqlStr)
	for rows.Next() {
		var user model.UserInfo
		if err1 := scanToStruct(rows, &user); err1 == nil {
			users = append(users, user)
			continue
		}
	}
	return &model.BatchUserResponse{
		Users: users,
	}, err
}

/// 单行查询
func query(db *sql.DB, query string, to interface{}, args ...interface{}) error {
	rows, err := db.Query(query, args...)
	if err != nil {
		fmt.Println(err)
		return err
	}
	for rows.Next() {
		if err1 := scanToStruct(rows, to); err1 == nil {
			continue
		}
	}

	if err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}
